//
//  MyCollectionViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/27.
//

#import "MyCollectionViewController.h"
#import "MyCollectionListCell.h"
#import <AVFoundation/AVFoundation.h>
#import "WordCollectListManager.h"
#import "WordListModel.h"
#import "WordDetialViewController.h"
#import "JPNavigationController.h"
#import "nuisdk/NeoNuiTts.h"
#import "AudioController.h"
#import <AdSupport/ASIdentifierManager.h>
#import "GetALiYunTokenManager.h"
#import "NeoNuiTtsManager.h"

@interface MyCollectionViewController ()<
UITableViewDelegate,
UITableViewDataSource,
///AVSpeechSynthesizerDelegate,
JPAPIManagerCallBackDelegate,
ConvVoiceRecorderDelegate,
NeoNuiTtsDelegate
>

@property(nonatomic,strong)UIButton *seeBtn;
@property(nonatomic,strong)UITableView *tableView;
//@property(nonatomic,strong)AVSpeechSynthesizer *synthesizer;
@property(nonatomic,strong)MyCollectionListCell *currentCell;
@property(nonatomic,assign)NSInteger playIndex;
@property(nonatomic,strong)WordCollectListManager *listManager;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)NeoNuiTts *nui;
@property(nonatomic,strong)AudioController *audioController;
@property (nonatomic, strong) dispatch_queue_t work_queue;
@property(nonatomic,strong)GetALiYunTokenManager *aLiYunTokenManager;
@property(nonatomic,strong)UIView *footerView;
@property(nonatomic,strong)AVPlayer *avPlayer;
@property(nonatomic,assign)BOOL isPlaying;

@end

@implementation MyCollectionViewController

-(WordCollectListManager *)listManager{
    if(!_listManager){
        _listManager = [[WordCollectListManager alloc]init];
        _listManager.delegate = self;
    }
    return _listManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(GetALiYunTokenManager *)aLiYunTokenManager{
    if(!_aLiYunTokenManager){
        _aLiYunTokenManager = [[GetALiYunTokenManager alloc]init];
        _aLiYunTokenManager.delegate = self;
    }
    return _aLiYunTokenManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.playIndex = -1;
    self.page = 1;
    [self createUI];
    [self loadData];
    
    [self initPlay];
    [self NuiTtsInit];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(wordDetialCollectRefresh:) name:@"WordDetialCollectRefresh" object:nil];
    
    //听力播放结束
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 重新设置 delegate 确保回调正常工作
    if (self.nui){
        self.nui.delegate = self;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}

#pragma mark - 语音合成播放需要
-(void)initPlay{
    
    self.audioController = [[AudioController alloc] init:only_player];
    self.audioController.delegate = self;
    [self.audioController setPlayerSampleRate:16000];// 16000返回音频的采样率
    
    self.work_queue = dispatch_queue_create("MyCollectionViewController_WorkQueue", DISPATCH_QUEUE_CONCURRENT);
    
}

#pragma mark - 语音合成初始化
-(void)NuiTtsInit{
    if (self.nui == NULL||self.nui == nil) {
        self.nui = [NeoNuiTtsManager sharedManager].nui;
        self.nui.delegate = self;
    }
    //请注意此处的参数配置，其中账号相关需要按照genInitParams的说明填入后才可访问服务
    NSString * initParam = [self genInitParams];
    int retcode = [self.nui nui_tts_initialize:[initParam UTF8String] logLevel:LOG_LEVEL_VERBOSE saveLog:YES];
    
    NSString *fontName = @"tomoka";
    [self.nui nui_tts_set_param:"font_name" value:[fontName UTF8String]];
    //在线合成
    [self.nui nui_tts_set_param:"mode_type" value:"2"]; // 必填
    NSString *speed_level = @"1";
    [self.nui nui_tts_set_param:"speed_level" value:[speed_level UTF8String]];
    NSString *pitch_level = @"0";
    [self.nui nui_tts_set_param:"pitch_level" value:[pitch_level UTF8String]];
    NSString *volume = @"2";
    [self.nui nui_tts_set_param:"volume)" value:[volume UTF8String]];
    // 字级别音素边界功能开关，该参数只对支持字级别音素边界接口的发音人有效。“1”表示打开，“0”表示关闭。
    [self.nui nui_tts_set_param:"enable_subtitle" value:"1"];
    
    if (retcode != 0) {
         TLog(@"init failed.retcode:%d", retcode);
         return;
    }
    
}

-(NSString *)genInitParams{
    NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
    NSString *bundlePath = [[NSBundle bundleWithPath:strResourcesBundle] resourcePath];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"voices"];
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        TLog(@"文件夹创建成功");
    }else{
        TLog(@"文件夹创建失败");
    }
    NSString *debug_path = testDirectory;
    NSMutableDictionary *ticketJsonDict = [NSMutableDictionary dictionary];
    [ticketJsonDict setObject:ALIYUNYUYINKEY forKey:@"app_key"];
    [self checkToken];
    NSString *TOKEN = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(!TOKEN){
        TOKEN = @"";
    }
    [ticketJsonDict setObject:TOKEN forKey:@"token"];
    
    //工作目录路径，SDK从该路径读取配置文件
    [ticketJsonDict setObject:bundlePath forKey:@"workspace"]; // 必填, 且需要有读写权限
//    TLog(@"workspace:%@", bundlePath);
    [ticketJsonDict setObject:debug_path forKey:@"debug_path"];
//    TLog(@"debug_path:%@", debug_path);

    [ticketJsonDict setObject:@"wss://nls-gateway.aliyuncs.com/ws/v1" forKey:@"url"]; // 默认

    // 设置成在线语音合成模式, 这个设置很重要, 遗漏会导致无法运行
    [ticketJsonDict setObject:@"2" forKey:@"mode_type"]; // 必填
    
    NSString *id_string = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    TLog(@"id: %s", [id_string UTF8String]);
    [ticketJsonDict setObject:id_string forKey:@"device_id"]; // 必填, 推荐填入具有唯一性的id, 方便定位问题

    NSData *data = [NSJSONSerialization dataWithJSONObject:ticketJsonDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark - 获取token
-(void)checkToken{
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(token){
        //token 存在 判断时间
        NSString *expireTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_EXPIRETIME"];
        if(expireTime){
            NSDate *currentDate = [NSDate date];
            NSTimeInterval expireTimeInterval = [expireTime doubleValue];
            NSDate *expireDate = [NSDate dateWithTimeIntervalSince1970:expireTimeInterval];
            if ([currentDate compare:expireDate] != NSOrderedAscending) {
                // 当前时间等于或在过期时间之后 已经到了过期时间
                [self.aLiYunTokenManager loadData];

            } else {
                // 当前时间在过期时间之前 还没到过期时间
            }
        }else{
            [self.aLiYunTokenManager loadData];
        }
    }else{
        [self.aLiYunTokenManager loadData];
    }
}

#pragma mark - 单词详情改变了收藏状态
-(void)wordDetialCollectRefresh:(NSNotification*)notifi{
    if(notifi.object){
        WordListModel *model = notifi.object;
        if(model.isCollect.integerValue == 0){
            for(NSInteger i = 0;i < self.dataArr.count;i++){
                WordListModel *model2 = self.dataArr[i];
                if([model.wordId isEqualToString:model2.wordId]){
                    [self.dataArr removeObjectAtIndex:i];
                    break;
                }
            }
            [self.tableView reloadData];
        }else{
            BOOL ishave = NO;
            for(NSInteger i = 0;i < self.dataArr.count;i++){
                WordListModel *model2 = self.dataArr[i];
                if([model.wordId isEqualToString:model2.wordId]){
                    ishave = YES;
                    break;
                }
            }
            if(ishave == NO){
                [self.dataArr insertObject:model atIndex:0];
                [self.tableView reloadData];
            }
        }
    }
}

-(void)loadData{
    self.listManager.page = [NSString stringWithFormat:@"%ld",self.page];
    self.listManager.type = @"1";
    [self.listManager loadData];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:@"我的收藏"];
    self.seeBtn = [[UIButton alloc]init];
    [self.seeBtn setImage:[UIImage imageNamed:@"mine_collect_see"] forState:UIControlStateNormal];
    [self.seeBtn setImage:[UIImage imageNamed:@"mine_collect_unsee"] forState:UIControlStateSelected];
    [self.seeBtn addTarget:self action:@selector(seeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:self.seeBtn];
    [self.seeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@34);
        make.right.mas_equalTo(@-11);
        make.bottom.mas_equalTo(@-5);
    }];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"MyCollectionListCell") forCellReuseIdentifier:@"MyCollectionListCell"];
    [self.view addSubview:self.tableView];
    
    __weak typeof(self)self_weak_ = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self_weak_.dataArr removeAllObjects];
        self_weak_.page = 1;
        [self_weak_ loadData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self_weak_.page++;
        [self_weak_ loadData];
    }];
    
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,kYMBottomH)];
    footerView.backgroundColor = [UIColor whiteColor];
    self.footerView = footerView;
    self.tableView.tableFooterView = footerView;
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.tableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            self.footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYMBottomH);
            self.tableView.tableFooterView = self.footerView;
            [self.tableView reloadData];
           
        });
    }
}

#pragma mark - 能不能看
-(void)seeBtnClick{
    self.seeBtn.selected = !self.seeBtn.selected;
    [self.tableView reloadData];
}

#pragma mark - tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCollectionListCell"];
    if(indexPath.row < self.dataArr.count){
        cell.isSel = self.seeBtn.selected;
        WordListModel *model = self.dataArr[indexPath.row];
        cell.wordModel = model;
        __weak typeof(self)self_weak_ = self;
        __weak typeof(cell)cell_weak_ = cell;
        [cell setPlayBlock:^{
            //停止正在播放的
            [self_weak_ stopSpeaking];
            self_weak_.currentCell = cell_weak_;
            if(indexPath.row == self_weak_.playIndex){
                //暂停
                self_weak_.playIndex = -1;
            }else{
                //播放
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self_weak_.playIndex = indexPath.row;
                    if(model.audio&&![model.audio isEqualToString:@""]){
                        [self_weak_ playAudio:model.audio];
                    }else{
                        if((model.pronunciation)&&(![model.pronunciation isEqualToString:@""])){
                            if((model.writing)&&(model.isReadWriting)&&([model.isReadWriting isEqualToString:@"1"]||model.isReadWriting.integerValue == 1)){
                                [self_weak_ speakJapaneseText:model.writing];
                            }else{
                                [self_weak_ speakJapaneseText:model.pronunciation];
                            }
                        }else{
                            if((model.writing)&&(![model.writing isEqualToString:@""])){
                                [self_weak_ speakJapaneseText:model.writing];
                            }
                        }
                    }
                });
            }
        }];
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.dataArr.count){
        [self stopSpeaking];
        WordListModel *model = self.dataArr[indexPath.row];
        model.isCollect = @"1";
        WordDetialViewController *vc = [[WordDetialViewController alloc]init];
        vc.wordModel = model;
        JPNavigationController *nav = [[JPNavigationController alloc]initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - 播放读取文本
- (void)speakJapaneseText:(NSString *)text{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
//    if(!self.synthesizer){
//        self.synthesizer = [[AVSpeechSynthesizer alloc] init];
//        self.synthesizer.delegate = self;
//    }
//    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
//    utterance.rate = 0.53; // 语速，范围0.0~1.0
//    utterance.pitchMultiplier = 1.1; // 音高，范围0.5~2.0
//    utterance.volume = 1.0; // 音量，范围0~1
//    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"ja-JP"];
//    utterance.voice = voice;
//    [self.synthesizer speakUtterance:utterance];
    
    
    dispatch_async(self.work_queue, ^{
        // 如果上个任务没有合成完毕，手动取消，开始合成新的任务
        [self.nui nui_tts_cancel:NULL];
        
        [self UpdateTtsParams:text];

        [self.nui nui_tts_play:"1" taskId:"" text:[text UTF8String]];
    });
    
}

#pragma mark - 更新语音合成参数配置
- (void)UpdateTtsParams:(NSString *)content {
    // 检查 self.nui 是否存在
    if (!self.nui) {
        NSLog(@"nui 对象为空，无法更新 TTS 参数");
        return;
    }
    if (!content) {
        NSLog(@"输入内容为空");
        return;
    }
    int chars = [self.nui nui_tts_get_num_of_chars:[content UTF8String]];
    if (chars > 300) {
        // 超过300字符设置成长文本语音合成模式
        [self.nui nui_tts_set_param:"tts_version" value:"1"];
    } else {
        // 未超过300字符设置成短文本语音合成模式
        [self.nui nui_tts_set_param:"tts_version" value:"0"];
    }
}


#pragma mark - tts callback
- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char*)taskid code:(int)code{
//    TLog(@"onNuiTtsEventCallback event[%d]", event);
    if (event == TTS_EVENT_START) {
//        TLog(@"onNuiTtsEventCallback TTS_EVENT_START");
        // 启动播放器
        [self.audioController startPlayer];
    } else if (event == TTS_EVENT_END || event == TTS_EVENT_CANCEL || event == TTS_EVENT_ERROR) {
        if (event == TTS_EVENT_END) {
//            TLog(@"onNuiTtsEventCallback TTS_EVENT_END");
            // 注意这里的event事件是指语音合成完成，而非播放完成，播放完成需要由audioController对象来进行通知
            [self.audioController drain];
        } else {
            // 取消播报、或者发生异常时终止播放
            if(self.audioController){
                [self.audioController stopPlayer];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(self.currentCell){
                    [self.currentCell stopVoiceAnimation];
                }
                self.playIndex =  -1;
            });
        }
        if (event == TTS_EVENT_ERROR) {
            const char *errmsg = [self.nui nui_tts_get_param: "error_msg"];
//            TLog(@"tts get errmsg:%s", errmsg);
            NSString *errorString = [NSString stringWithUTF8String:errmsg];
            if ([errorString containsString:@"144003"]) {
               //token过期
                [self.aLiYunTokenManager loadData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成token过期，已重新获取，请再次点击播放"];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成失败"];
                });
            }
        }
      
    }
}

- (void)onNuiTtsUserdataCallback:(char*)info infoLen:(int)info_len buffer:(char*)buffer len:(int)len taskId:(char*)task_id {
    TLog(@"onNuiTtsUserdataCallback info ...");
    if (info_len > 0) {
        TLog(@"onNuiTtsUserdataCallback info text %s. index %d.", info, info_len);
    }
    if (len > 0) {
        [self.audioController write:(char*)buffer Length:(unsigned int)len];
    }
}

-(void)onNuiTtsVolumeCallback:(int)volume taskId:(char*)task_id{
    
}

#pragma mark - Audio Player Delegate
-(void)playerDidFinish {
    //播放数据被实际播放完成后回调。
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.currentCell){
            [self.currentCell stopVoiceAnimation];
        }
        self.playIndex =  -1;
    });
}

//语音合成完成
-(void)playerDrainDataFinish{
   
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.audioController.isPlayerStopped == YES){
            if(self.currentCell){
                [self.currentCell stopVoiceAnimation];
            }
            self.playIndex =  -1;
        }
    });

}


#pragma mark - 停止当前正在读的文本
- (void)stopSpeaking{
//    if (self.synthesizer&&self.synthesizer.isSpeaking) {
//        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
//        if(self.currentCell){
//            [self.currentCell stopVoiceAnimation];
//        }
//    }
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController stopPlayer];
    }
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
    }
    
    if(self.avPlayer){
        self.isPlaying = NO;
        [self.avPlayer pause];
        [self.avPlayer seekToTime:kCMTimeZero];
    }
    
}


#pragma mark - 单词音频播放
-(void)playAudio:(NSString *)audio{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:audio]];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    if(self.avPlayer){
        [self.avPlayer pause];
        [self.avPlayer replaceCurrentItemWithPlayerItem:item];
    }else{
        self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    }
    [self.avPlayer play];
    self.isPlaying = YES;
}

-(void)playToEndTime:(NSNotification*)notifi{
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
    }
    self.playIndex =  -1;
    [self.avPlayer seekToTime:kCMTimeZero];
    self.isPlaying = NO;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"播放成功");
            
        } else if (status == AVPlayerItemStatusFailed) {
            NSLog(@"播放失败");
            [JPProgressHUD showMsg:@"播放失败"];
            if(self.currentCell){
                [self.currentCell stopVoiceAnimation];
            }
            self.playIndex =  -1;
        }
    }
}

//#pragma mark - AVSpeechSynthesizer deletage
//- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
//    // 当前文本已经读完
//    if(self.currentCell){
//        [self.currentCell stopVoiceAnimation];
//    }
//    self.playIndex =  -1;
//}


#pragma mark - 设置静音模式下也能播放音频
-(void)listentTypeSet{
    // 获取当前的音频会话类别
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    // 检查当前类别是否已经是 AVAudioSessionCategoryPlayback
    if (![audioSession.category isEqualToString:AVAudioSessionCategoryPlayback]) {
        NSError *setCategoryError = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
        
        if (setCategoryError) {
            NSLog(@"Error setting category: %@", [setCategoryError localizedDescription]);
        }
    }
    
    // 检查音频会话是否已经处于激活状态
    if (!audioSession.isOtherAudioPlaying) {
        NSError *activationError = nil;
        [audioSession setActive:YES error:&activationError];
        
        if (activationError) {
            NSLog(@"Error activating session: %@", [activationError localizedDescription]);
        }
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.listManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [WordListModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"list"]];
        NSString *count = [NSString stringWithFormat:@"%@",dic[@"data"][@"count"]];
        [self.dataArr addObjectsFromArray:arr];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        if(self.dataArr.count == count.integerValue){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        
    }
    
    if([manager isEqual:self.aLiYunTokenManager]){
         NSDictionary *dic = manager.response.content;
         if(dic[@"data"][@"token"]){
             NSString *token = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"]];
             [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"ALIYUN_YUYIN_TOKEN"];
         }
         if(dic[@"data"][@"expireTime"]){
             NSString *expireTime = [NSString stringWithFormat:@"%@",dic[@"data"][@"expireTime"]];
             [[NSUserDefaults standardUserDefaults]setObject:expireTime forKey:@"ALIYUN_YUYIN_EXPIRETIME"];
         }
         if (self.nui) {
           [self.nui nui_tts_release];
           self.nui = nil;
         }
         [self NuiTtsInit];
    }
    
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


-(void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    // 若_nui未进行释放, 下次进入此view使用的_nui处于已初始化,
    // 则再调用nui_tts_initialize无法覆盖已经设置的参数.
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}


@end
